world.addCollisionFilter('player', 'player');
import { loadPlayer,leaderBoard,savePlayer,initPlayer,getPlayerData,deletePlayer,deleteAllData } from "./SQL";
import { openBag,find_things_informations_by_id,bag_show_list,get_thing_name_by_id } from "./bag";
import { useZswq } from "./attack";
import { jl3D,jl2D } from "./jl";
import { information,add_uiShow,uiHp } from "./ui";
import { things,make_book,enemy } from "./data";
import { creatZone,spawnSDMS } from "./boss";
import { small_emery } from "./small_emery";
import { useFswq } from "./fsAttack";
import { fishShop } from "./fishShop";
information();uiHp();fishShop();
const admin = ['253713214099538'/*稳稳的小鹿9m2*/, '50373975'/*可爱的胖头鱼*/,'50408417'/*稳稳的小鹿9m*/]
world.onChat(({ entity, message }) => {
    if (message[0] == '$' && admin.includes(entity.player.userId)) {
        try {
            world.say('<~' + eval(message.slice(1)))
        } catch (error) {
            world.say('<~' + error)
        }
    }
})

export function find_by_playerName(name:string){
    let player:GamePlayerEntity = null;
    world.querySelectorAll('player').forEach((e)=>{
        if (e.player.name === name){
            player = e ;
        }
    })
    return player;
}

function isNumeric(str:string) {
    const num = Number(str);
    return !Number.isNaN(num) && num === num; // 检查是否为NaN以及是否为无穷大（Infinity）的另一种形式，因为Infinity也是Number但不是NaN。
}
 

/**
 * 将该字符串转换为数字类型
 * @param str 字符串
 * @returns 数字（如果不是数字则会返回null）
 */
function convertToNumber(str:string) {
    if (isNumeric(str)) {
        return Number(str); // 直接使用Number转换，适用于整数和浮点数。
    }
    return null; // 或者返回NaN或其他错误指示。
}
 


export function sjexp(level:number){
    return level*100+1000*(Math.floor(level/10))
}

// 非玩家的实体被创建时，广播一条消息
world.onEntityCreate(({ entity }) => {
  if (entity.player) { return }  // 如果实体是玩家类型则跳过
  setTimeout(() => {
    if (entity.hasTag('canhurt')){
    entity.enableDamage = true;
    entity.hurtList = [];
    entity.hurtList_player = [];
    entity.takeDamage_by_player = function(number:number,attacker:GamePlayerEntity) {
        entity.hurt(number);
        let new_create = true;
        entity.hurtList_player.forEach(e=>{
            if (e.entity === attacker){
                e.number += number;
                new_create = false;
            }
        })
        const dentity ={
            entity:attacker,
            number:number,
        }
        if (new_create){
            entity.hurtList_player.push(dentity);
        }
    }
    entity.takeDamage_by_entity = function(number:number,attacker:GameEntity) {
        entity.hurt(number);
        let new_create = true;
        entity.hurtList.forEach(e=>{
            if (e.entity === attacker){
                e.number += number;
                new_create = false;
            }
        })
        const dentity ={
            entity:attacker,
            number:number,
        }
        if (new_create){
            entity.hurtList.push(dentity);
        }
    }
    }
  }, 200);
})


/*
world.onPlayerJoin(async ({ entity }) => { // 玩家进入地图后
    await loadPlayer(entity); // 读档
});
*/
world.onPlayerLeave(async ({ entity }) => { // 玩家离开地图后
    entity.save != false ? await savePlayer(entity) : null; // 存档
})





world.onPlayerJoin(({entity})=>{
    entity.addTag('canhurt');
    entity.hurtList = [];
    entity.hurtList_player = [];
    entity.canJy = true;
    entity.add = function(item,show_ui) {
        // 实现方法需要通过其他方式（如函数赋值）
        let new_create = true;
        entity.bagList.forEach(x=>{
            if (x.id === item.id){
                x.number+=item.number;
                new_create = false;
            }
        })
        if (new_create){
            entity.bagList.push(item);
        }
        if (show_ui){
            add_uiShow(find_things_informations_by_id(item.id).name+'*'+item.number,entity);
        }
    }
    entity.delete = function(item) {
        const index = entity.bagList.findIndex(x => x.id === item.id);
        if (!entity.bagList[index]) return false;
        if (entity.bagList[index].number<item.number) return false;
        entity.bagList[index].number-=item.number;
        if (entity.bagList[index].number <= 0) {
            entity.bagList.splice(index, 1);  // 正确删除空槽位
        }
        return true;
    }
    entity.things_num = function(id) {
        // 实现方法需要通过其他方式（如函数赋值）
        let num = 0;
        entity.bagList.forEach(x=>{
            if (x.id === id){
                num = x.number;
            }
        })
        return num;
    }
    entity.takeDamage_by_entity = function(number:number,attacker:GameEntity) {
        let damage = number*(1-entity.fy);
        entity.hurt(damage);
        let new_create = true;
        entity.hurtList.forEach(e=>{
            if (e.entity === attacker){
                e.number += damage;
                new_create = false;
            }
        })
        const dx ={
            entity:attacker,
            number:damage,
        }
        if (new_create){
            entity.hurtList.push(dx);
        }
    }
    entity.takeDamage_by_player = function(number:number,attacker:GamePlayerEntity) {
        let damage = number*(1-entity.fy);
        entity.hurt(damage);
        let new_create = true;
        entity.hurtList_player.forEach(e=>{
            if (e.entity === attacker){
                e.number += damage;
                new_create = false;
            }
        })
        const dx ={
            entity:attacker,
            number:damage,
        }
        if (new_create){
            entity.hurtList_player.push(dx);
        }
    }
})//玩家add与delete与things_num实现

world.onPlayerJoin(async({entity})=>{
    await loadPlayer(entity); // 读档
    if (!entity.sign){
        entity.sign = 0;
    }
    if (!entity.lingshi) {
        entity.lingshi = 0;
    }
    if (!entity.fswq) {
        entity.fswq = 0; // 玩家副手武器
    }
    if (entity.level === 0){
        entity.bagList = [];
        entity.coin = 100;
        entity.level = 1;
    }
    savePlayer(entity);
    entity.fy = (find_things_informations_by_id(entity.fswq).fy ); // 设置玩家防御力
    entity.hp = entity.maxHp = (entity.level-1)*10+100;
    entity.canAttack = true;
    entity.canFsAttack = true;
    entity.enableDamage = true;
    //entity.player.scale = 0.8;
    entity.player.jumpPower = 0.6;
    entity.player.enableDoubleJump = true;
    entity.player.jumpSpeedFactor = 1.2;
    entity.player.jumpAccelerationFactor = 1;
    entity.player.doubleJumpPower = 0.6;
    //entity.player.runSpeed = 0.33;
    //entity.player.runAcceleration = 0.31;
    //entity.player.walkSpeed = 0.20;
    //entity.player.walkAcceleration = 0.15;
    //entity.player.crouchSpeed = 0.11;
    //entity.player.crouchAcceleration = 0.10;
    entity.onDie(async ()=>{
        await entity.player.dialog<GameSelectDialogParams>({
            type: GameDialogType.SELECT,
            title: '你倒下了',
            content: `请时刻注意你的血量!`,
            titleBackgroundColor: new GameRGBAColor(0.95,0.54,0.54,1.00),
            contentBackgroundColor: new GameRGBAColor(0.89,0.89,0.89,1.00),
            options: ['确定'],
        });
        entity.player.forceRespawn();
    })
    entity.hurtList = [];
    entity.player.addWearable({
        bodyPart: GameBodyPart.RIGHT_HAND,
        mesh: find_things_informations_by_id(entity.zswq).mesh,
        orientation: new GameQuaternion(0, 1, 0, 0).rotateY(Math.PI/2),
        scale: new GameVector3(0.5, 0.5, 0.5),
        offset: new GameVector3(0, 0, 0),
    });
    entity.player.addWearable({
        bodyPart: GameBodyPart.LEFT_HAND,
        mesh: find_things_informations_by_id(entity.fswq).mesh,
        orientation: new GameQuaternion(0, 1, 0, 0).rotateY(Math.PI/2),
        scale: new GameVector3(1, 1, 1),
        offset: new GameVector3(0, 0, 0),
    });
    await entity.player.dialog<GameSelectDialogParams>({
            type: GameDialogType.SELECT,
            title: entity.player.name,
            content: `欢迎进入地图!
关闭此对话框就可以正式开始游玩！
<关闭后同步开启UI>`,
            titleBackgroundColor: new GameRGBAColor(0.93, 0.95, 0.54, 1.0),
            contentBackgroundColor: new GameRGBAColor(0.54, 0.68, 0.95, 1.0),
            options: ['确定'],
        });
    remoteChannel.sendClientEvent(entity, {
        type: 'ok',
        data: {
            text: 'text',
        }
    })
})






world.onPress(async({entity,button,raycast})=>{
    if (button === GameButtonType.ACTION1){
        if (entity.player.walkState === GamePlayerWalkState.CROUCH){
            openBag(entity)
        }else{
            useFswq(entity,entity.fswq,raycast,{
                yaw: entity.player.cameraYaw,
                pitch: entity.player.cameraPitch,
            });
        }
    }else if (button === GameButtonType.ACTION0){
        useZswq(entity,entity.zswq,raycast,{
            yaw: entity.player.cameraYaw,
            pitch: entity.player.cameraPitch,
        });
    }
})


world.querySelectorAll('.canhurt').forEach(x=>{
    x.enableDamage = true;
    x.hurtList = [];
    x.hurtList_player = [];
    x.takeDamage_by_player = function(number:number,attacker:GamePlayerEntity) {
        x.hurt(number);
        let new_create = true;
        x.hurtList_player.forEach(e=>{
            if (e.entity === attacker){
                e.number += number;
                new_create = false;
            }
        })
        const dx ={
            entity:attacker,
            number:number,
        }
        if (new_create){
            x.hurtList_player.push(dx);
        }
    }
    x.takeDamage_by_entity = function(number:number,attacker:GameEntity) {
        x.hurt(number);
        let new_create = true;
        x.hurtList.forEach(e=>{
            if (e.entity === attacker){
                e.number += number;
                new_create = false;
            }
        })
        const dx ={
            entity:attacker,
            number:number,
        }
        if (new_create){
            x.hurtList.push(dx);
        }
    }
})

async function receive_drops(entity:GamePlayerEntity,id:number) {
    eval(enemy[id].instruction);
}



setInterval(()=>{
    world.querySelectorAll('player').forEach(async(e)=>{
        if (e.exp>=sjexp(e.level) && e.level!==0){
            e.exp-=sjexp(e.level);
            e.level+=1;
            e.hp = e.maxHp = (e.level-1)*10+100;
            e.player.directMessage('恭喜你升到了'+e.level+'级');
            Object.assign(e, {
                particleRate: 130,
                particleSize: [12, 14, 18, 14, 20],
                particleColor: [
                    new GameRGBColor(100, 100, 100),
                    new GameRGBColor(90, 90, 90),
                    new GameRGBColor(80, 80, 80),
                ],
                particleLifetime: 5,
                particleVelocitySpread: new GameVector3(0.5, 0.5, 0.5),
            })
            await sleep(100);
            e.particleRate = 0;
        }
    })
},100)




const tpPlaces:string[] = ['灵石之岛', '中心岛', '湖中村社','树鹅之岛','南部山丘','空中小岛','北部活动平原','<晴空雀>挑战传送'];
let positions: {place: string,position:GameVector3}[] = [];


tpPlaces.forEach((e) => {
  const selector = `.${e}`;
  const element = world.querySelectorAll(selector)[0];
  
  if (element) {
    positions.push({
      place: e,
      position: element.position
    });
  } else {
    console.warn(`找不到位置: ${selector}`); // 添加错误处理
  }
});
/*
const index = entity.bagList.findIndex(x => x.id === item.id);

        entity.bagList[index].number-=item.number;
        if (entity.bagList[index].number === 0) {
            entity.bagList.splice(index, 1);  // 正确删除空槽位
        }
*/
world.querySelectorAll('.传送法阵').forEach((e)=>{
    let place = '';
    tpPlaces.forEach((names)=>{
        if (e.hasTag(names)){
            place=names;
        }
    })
    const index = tpPlaces.findIndex(x => x === place);
    let show_tpPlaces = tpPlaces;
    //show_tpPlaces.splice(index,1);
    e.enableInteract = true;
    e.interactRadius = 3;
    e.interactColor = new GameRGBColor(255,255,255);
    e.onInteract(async ({entity})=>{
        const tp = await entity.player.dialog<GameSelectDialogParams>({
            type: GameDialogType.SELECT,
            title: place,
            content: `你要传送去哪里？`,
            titleBackgroundColor: new GameRGBAColor(0.93, 0.95, 0.54, 1.0),
            contentBackgroundColor: new GameRGBAColor(0.54, 0.68, 0.95, 1.0),
            options: show_tpPlaces,
        });
        if (!tp) return;
        entity.position.copy(positions[positions.findIndex(x => x.place===tp.value)].position)
    })
})


const shop = world.querySelector('#商店老板');
shop.enableInteract = true;
shop.interactRadius = 3;
shop.interactHint = '商店老板';
shop.interactColor = new GameRGBColor(255,255,255);
shop.onInteract(async({entity})=>{
    const xx = await entity.player.dialog<GameSelectDialogParams>({
        type: GameDialogType.SELECT,
        title:  '商店老板',
        content: `你好！${entity.player.name}
欢迎来到商店，看看有什么你要买的？
哦对了，我右边的锤子可以将图纸合成为实物哦`,
        //titleBackgroundColor: new GameRGBAColor(0.93, 0.95, 0.54, 1.0),
        //contentBackgroundColor: new GameRGBAColor(0.54, 0.68, 0.95, 1.0),
        options: ['金币商店',/*'<雷光一现>开服限时活动'*/'<防具>抽奖','兑换灵石'],
    });
    if (!xx) return;
    if (xx.value === '金币商店'){
        const shop_things:string[] = ['木剑*1——100金币','木材*1——100金币','生铁*1——500金币','熟铁*1——1000金币','烈火凌云制作图*1——300金币','木盾制作图*1——100金币'];
        const price:number[] = [100,100,500,1000,300,100];
        const give_things:{id:number,number:number}[] = [{id:2,number:1},{id:7,number:1},{id:8,number:1},{id:9,number:1},{id:10,number:1},{id:21,number:1}];
        const t = await entity.player.dialog<GameSelectDialogParams>({
            type: GameDialogType.SELECT,
            title:  '商店老板',
            content: `请选择你要购买的物品`,
            //titleBackgroundColor: new GameRGBAColor(0.93, 0.95, 0.54, 1.0),
            //contentBackgroundColor: new GameRGBAColor(0.54, 0.68, 0.95, 1.0),
            options: shop_things,
        });
        if (!t) return;
        if (entity.coin>=price[t.index]){
            entity.coin-=price[t.index];
            entity.add(give_things[t.index],true);
            entity.player.directMessage('购买成功！');
        }else{
            entity.player.directMessage('金币不足！');
        }
    }else if (xx.value === '<雷光一现>开服限时活动'){
        const shop_things:string[] = ['<雷光一现>开服限时活动抽奖次数*1——金币*1000','雷光核心*1——1000金币'];
        const price:number[] = [1000,1000];
        const give_things:{id:number,number:number}[] = [{id:15,number:1},{id:12,number:1}];
        const t = await entity.player.dialog<GameSelectDialogParams>({
            type: GameDialogType.SELECT,
            title:  '商店老板',
            content: `请选择你要购买的物品`,
            //titleBackgroundColor: new GameRGBAColor(0.93, 0.95, 0.54, 1.0),
            //contentBackgroundColor: new GameRGBAColor(0.54, 0.68, 0.95, 1.0),
            options: shop_things,
        });
        if (!t) return;
        if (entity.coin>=price[t.index]){
            entity.coin-=price[t.index];
            entity.add(give_things[t.index],true);
            entity.player.directMessage('购买成功！');
        }else{
            entity.player.directMessage('金币不足！');
        }
    }
    else if (xx.value === '<防具>抽奖'){
        const shop_things:string[] = ['<防具>抽奖次数*1——金币*1000'];
        const price:number[] = [1000];
        const give_things:{id:number,number:number}[] = [{id:22,number:1}];
        const t = await entity.player.dialog<GameSelectDialogParams>({
            type: GameDialogType.SELECT,
            title:  '商店老板',
            content: `请选择你要购买的物品`,
            //titleBackgroundColor: new GameRGBAColor(0.93, 0.95, 0.54, 1.0),
            //contentBackgroundColor: new GameRGBAColor(0.54, 0.68, 0.95, 1.0),
            options: shop_things,
        });
        if (!t) return;
        if (entity.coin>=price[t.index]){
            entity.coin-=price[t.index];
            entity.add(give_things[t.index],true);
            entity.player.directMessage('购买成功！');
        }else{
            entity.player.directMessage('金币不足！');
        }
    }else if (xx.value === '兑换灵石'){
        const num = await entity.player.dialog<GameInputDialogParams>({
                type: GameDialogType.INPUT,
                title: '兑换灵石',
                content: `你要兑换多少灵石？\n每个灵石需要15000金币`,
                titleBackgroundColor: new GameRGBAColor(1.00,1.00,1.00,1.00),
                contentBackgroundColor: new GameRGBAColor(0.00,0.00,0.00,1.00),
        });
        if (!convertToNumber(num)){
            entity.player.directMessage('你输入错误，兑换终止!');
            return;
        }
        if (num.includes('.')){
            entity.player.directMessage('你输入错误，兑换终止!');
            return;
        }
        const Tnum=convertToNumber(num);
        if (Tnum*15000>entity.coin){
            entity.player.directMessage('你没有这么多金币，兑换终止!');
            return;
        }
        if (Tnum<=0){
            entity.player.directMessage('你输入错误，兑换终止!');
            return;
        }
        entity.coin-=Tnum*15000;
        entity.lingshi+=Tnum;
        entity.player.directMessage('兑换成功！你花费了'+Tnum*15000+'金币兑换了'+Tnum+'个灵石');
    }
})


const duanzao = world.querySelector('#锻造');
duanzao.enableInteract = true;
duanzao.interactRadius = 3;
duanzao.interactHint = '锻造';
duanzao.interactColor = new GameRGBColor(255,255,255);
duanzao.onInteract(async({entity})=>{
    var show_map:string[] = [];
    var map_list:number[] = [];
    entity.bagList.forEach((e)=>{
        if (find_things_informations_by_id(e.id).type === 'make_map'){
            show_map.push(get_thing_name_by_id(e.id));
            map_list.push(e.id);
        }
    })
    if (map_list.length==0){
            await entity.player.dialog<GameSelectDialogParams>({
                type: GameDialogType.SELECT,
                title: '锻造',
                content: `你的背包里没有图纸!`,
                titleBackgroundColor: new GameRGBAColor(0.93, 0.95, 0.54, 1.0),
                contentBackgroundColor: new GameRGBAColor(0.54, 0.68, 0.95, 1.0),
                options: ['确定'],
            });
            return;
        }
    const xx = await entity.player.dialog<GameSelectDialogParams>({
        type: GameDialogType.SELECT,
        title:  '锻造',
        content: `你好！${entity.player.name}
请选择你要锻造的物品`,
        //titleBackgroundColor: new GameRGBAColor(0.93, 0.95, 0.54, 1.0),
        //contentBackgroundColor: new GameRGBAColor(0.54, 0.68, 0.95, 1.0),
        options: show_map,
    });
    if (!xx) return;
    let cllb:string = '';//展示材料列表 
    let check_list:{id:number,number:number}[] = [];//材料列表(核实材料是否足够使用) 
    make_book[map_list[xx.index]].need.forEach((e: { id: number; number: number; }) => {
        cllb += ('\n'+get_thing_name_by_id(e.id)+'*'+String(e.number));
        check_list.push(e);
    });
    const hc = await entity.player.dialog<GameSelectDialogParams>({
        type: GameDialogType.SELECT,
        title: xx.value,
        content: `需要材料：${cllb}`,
        //titleBackgroundColor: new GameRGBAColor(0.93, 0.95, 0.54, 1.0),
        //contentBackgroundColor: new GameRGBAColor(0.54, 0.68, 0.95, 1.0),
        options: ['合成','取消'],
    });
    if (!hc) return;
    if (hc.value === '取消') return;
    let can_hc:boolean = true;
    check_list.forEach((e)=>{
        if (entity.things_num(e.id)<e.number){
            can_hc = false;
        }
    })
    if (can_hc){
        check_list.forEach((e)=>{
            entity.delete(e);
        })
        entity.delete({id:map_list[xx.index],number:1});
        entity.add(make_book[map_list[xx.index]].give,true);
        entity.player.directMessage('合成成功！');
    }else {
        entity.player.directMessage('材料不足，无法合成！');
    }
})

const cj = world.querySelector('.抽奖');
/**
 * 抽奖奖池列表
 */
const cjList:{name:string,needChanceId:number}[] = [{name:'<雷光一现>开服限时活动',needChanceId:15},{name:'<防具>抽奖',needChanceId:22}];
const cjjl:{id:number,number:number,gl:number}[][] = [
    [{id:11,number:1,gl:0.005},{id:14,number:1,gl:0.01},{id:13,number:1,gl:0.285},{id:3,number:1,gl:0.2},{id:7,number:5,gl:0.5}],
    [{id:19,number:1,gl:0.005},{id:20,number:1,gl:0.195},{id:7,number:5,gl:0.4},{id:8,number:5,gl:0.3},{id:9,number:5,gl:0.1}]
];
const cjneed:{id:number,number:number}[] = [{id:15,number:1},{id:22,number:1}];
cj.enableInteract = true;
cj.showEntityName = true;
cj.id = '抽奖';
cj.showEntityName = true;
cj.nameRadius = 6;
cj.interactColor = new GameRGBColor(1.00,1.00,1.00);
cj.interactRadius = 10;
cj.interactHint = '抽奖';
cj.onInteract(async({entity})=>{
    let jcShowList:string[] = [];
    let cjjlShowList:string = '';
    cjList.forEach((x)=>{
        jcShowList.push(x.name);
    })
    const xx = await entity.player.dialog<GameSelectDialogParams>({
        type: GameDialogType.SELECT,
        title: '抽奖',
        content: `你好！${entity.player.name}
请问你要进行什么抽奖？`,
        titleBackgroundColor: new GameRGBAColor(0.00,0.25,1.00,1.00),
        contentBackgroundColor: new GameRGBAColor(0.00,0.72,1.00,1.00),
        options: jcShowList,
    });
    if (!xx) return;
    cjjl[xx.index].forEach((x)=>{
        cjjlShowList+=get_thing_name_by_id(x.id)+'*'+x.number+'——'+x.gl*100+'%\n';
    })
    const isC = await entity.player.dialog<GameSelectDialogParams>({
        type: GameDialogType.SELECT,
        title: jcShowList[xx.index],
        content: cjjlShowList+'你要进行此抽奖吗？',
        titleBackgroundColor: new GameRGBAColor(0.00,0.25,1.00,1.00),
        contentBackgroundColor: new GameRGBAColor(0.00,0.72,1.00,1.00),
        options: ['确定'],
    });
    if (!isC) return;
    let tt = cjneed[xx.index];
    
    if (!entity.delete(tt)){
        entity.player.directMessage('抽奖机会不足');
        return;
    }
    const rand = Math.random();
    let tmp = 0;
    let cancj = true;
    console.log(rand);
    cjjl[xx.index].forEach((x)=>{
        tmp+=x.gl;
        if (rand<=tmp&&cancj){
            console.log(get_thing_name_by_id(x.id));
            entity.add({id:x.id,number:x.number},true);
            world.say('恭喜玩家<'+entity.player.name+'>在抽奖中获得了'+get_thing_name_by_id(x.id)+'*'+x.number+'!');
            cancj=false;
        }
    })
})

spawnSDMS();
small_emery();


const jiaoyi = world.querySelector('.交易');
jiaoyi.enableInteract = true;
jiaoyi.interactRadius = 6;
jiaoyi.interactHint = '交易';
jiaoyi.interactColor = new GameRGBColor(255,255,255);
jiaoyi.showEntityName = true;
jiaoyi.onInteract(async({entity})=>{
    if (!entity.canJy){
        return;
    }
    entity.canJy = false;
    let player_list:GamePlayerEntity[] = [];
    let show_player_list:string[] = [];
    world.querySelectorAll('player').forEach((e)=>{
        if (e!==entity){
            player_list.push(e);
            show_player_list.push(e.player.name);
        }
    })
    const people2 = await entity.player.dialog<GameSelectDialogParams>({
        type: GameDialogType.SELECT,
        title: '交易',
        content: `你好！${entity.player.name}
请问你要与谁进行交易？`,
        titleBackgroundColor: new GameRGBAColor(1.00,1.00,1.00,1.00),
        contentBackgroundColor: new GameRGBAColor(0.00,0.00,0.00,1.00),
        options: show_player_list,
    });
    if (!people2){
        entity.player.directMessage('取消交易!');
        entity.canJy = true;
        return;
    }else {
        const customer=find_by_playerName(people2.value);
        if (!customer){
            entity.player.directMessage('该玩家未找到!');
            entity.canJy = true;
            return;
        }
        if (!customer.canJy){
            entity.player.directMessage('对方暂时无法交易!');
            entity.canJy = true;
            return;
        }
        entity.player.directMessage('已向对方发起交易请求......');
        const isAgree = await customer.player.dialog<GameSelectDialogParams>({
            type: GameDialogType.SELECT,
            title: '交易',
            content: `你好！${entity.player.name} 向你发起交易请求
请问你同意与其进行交易吗？`,
            titleBackgroundColor: new GameRGBAColor(1.00,1.00,1.00,1.00),
            contentBackgroundColor: new GameRGBAColor(0.00,0.00,0.00,1.00),
            options: ['同意','取消'],
        });
        if (!isAgree){
            entity.player.directMessage('对方忽略了你的请求!');
            entity.canJy = true;
            return;
        }
        if (isAgree.value === '取消'){
            entity.player.directMessage('对方拒绝与你交易!');
            entity.canJy = true;
            return;
        }
        customer.canJy = false;
        const type1 = await entity.player.dialog<GameSelectDialogParams>({
            type: GameDialogType.SELECT,
            title: '交易',
            content: `你要给他什么`,
            titleBackgroundColor: new GameRGBAColor(1.00,1.00,1.00,1.00),
            contentBackgroundColor: new GameRGBAColor(0.00,0.00,0.00,1.00),
            options: ['金币','物品','不给'],
        });
        if (!type1){
            entity.player.directMessage('交易终止!');
            customer.player.directMessage('交易终止!');
            entity.canJy = true;customer.canJy = true;
            return;
        }
        const type2 = await customer.player.dialog<GameSelectDialogParams>({
            type: GameDialogType.SELECT,
            title: '交易',
            content: `你要给他什么`,
            titleBackgroundColor: new GameRGBAColor(1.00,1.00,1.00,1.00),
            contentBackgroundColor: new GameRGBAColor(0.00,0.00,0.00,1.00),
            options: ['金币','物品','不给'],
        });
        if (!type2){
            entity.player.directMessage('交易终止!');
            customer.player.directMessage('交易终止!');
            entity.canJy = true;customer.canJy = true;
            return;
        }
        let jb1:number = 0;let jb2:number = 0;
        let things1:{id:number,number:number}  = {id:0,number:0}; let things2:{id:number,number:number}  = {id:0,number:0}; 
        if (type1.value === '金币'){
            const num = await entity.player.dialog<GameInputDialogParams>({
                type: GameDialogType.INPUT,
                title: '交易',
                content: `你要给对方多少个金币`,
                titleBackgroundColor: new GameRGBAColor(1.00,1.00,1.00,1.00),
                contentBackgroundColor: new GameRGBAColor(0.00,0.00,0.00,1.00),
            });
            if (!convertToNumber(num)){
                entity.player.directMessage('你输入错误，交易终止!');
                customer.player.directMessage('对方输入错误，交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
            if (num.includes('.')){
                entity.player.directMessage('你输入错误，交易终止!');
                customer.player.directMessage('对方输入错误，交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
            jb1=convertToNumber(num);
            if (jb1>entity.coin){
                entity.player.directMessage('你没有这么多金币，交易终止!');
                customer.player.directMessage('对方拥有金币数量不足，交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
            if (jb1<=0){
                entity.player.directMessage('你输入错误，交易终止!');
                customer.player.directMessage('对方输入错误，交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
        }else if (type1.value === '物品'){
            var show_list = bag_show_list(entity.bagList);
            if (show_list.length === 0){
                entity.player.directMessage('你的背包里没有物品，交易终止!');
                customer.player.directMessage('对方无可交易物品，交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
            const bager = await entity.player.dialog<GameSelectDialogParams>({
                type: GameDialogType.SELECT,
                title: '交易',
                content: `你要给对方什么物品`,
                titleBackgroundColor: new GameRGBAColor(1.00,1.00,1.00,1.00),
                contentBackgroundColor: new GameRGBAColor(0.00,0.00,0.00,1.00),
                options: show_list,
            });
            if (!bager){
                entity.player.directMessage('交易终止!');
                customer.player.directMessage('交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
            things1.id = entity.bagList[bager.index].id;
            const num = await entity.player.dialog<GameInputDialogParams>({
                type: GameDialogType.INPUT,
                title: '交易',
                content: `你要给对方多少个物品`,
                titleBackgroundColor: new GameRGBAColor(1.00,1.00,1.00,1.00),
                contentBackgroundColor: new GameRGBAColor(0.00,0.00,0.00,1.00),
            });
            if (!convertToNumber(num)){
                entity.player.directMessage('你输入错误，交易终止!');
                customer.player.directMessage('对方输入错误，交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
            if (num.includes('.')){
                entity.player.directMessage('你输入错误，交易终止!');
                customer.player.directMessage('对方输入错误，交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
            things1.number = convertToNumber(num);
            if (things1.number>entity.things_num(things1.id)){
                entity.player.directMessage('你没有这么多物品，交易终止!');
                customer.player.directMessage('对方交易物品数量不足，交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
            if (things1.number<=0){
                entity.player.directMessage('你输入错误，交易终止!');
                customer.player.directMessage('对方输入错误，交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
        }
        if (type2.value === '金币'){
            const num = await customer.player.dialog<GameInputDialogParams>({
                type: GameDialogType.INPUT,
                title: '交易',
                content: `你要给对方多少个金币`,
                titleBackgroundColor: new GameRGBAColor(1.00,1.00,1.00,1.00),
                contentBackgroundColor: new GameRGBAColor(0.00,0.00,0.00,1.00),
            });
            if (!convertToNumber(num)){
                customer.player.directMessage('你输入错误，交易终止!');
                entity.player.directMessage('对方输入错误，交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
            if (num.includes('.')){
                customer.player.directMessage('你输入错误，交易终止!');
                entity.player.directMessage('对方输入错误，交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
            jb2=convertToNumber(num);
            if (jb2>customer.coin){
                customer.player.directMessage('你没有这么多金币，交易终止!');
                entity.player.directMessage('对方拥有金币数量不足，交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
            if (jb2<=0){
                customer.player.directMessage('你输入错误，交易终止!');
                entity.player.directMessage('对方输入错误，交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
        }else if (type2.value === '物品'){
            var show_list = bag_show_list(customer.bagList);
            if (show_list.length === 0){
                customer.player.directMessage('你的背包里没有物品，交易终止!');
                entity.player.directMessage('对方无可交易物品，交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
            const bager = await customer.player.dialog<GameSelectDialogParams>({
                type: GameDialogType.SELECT,
                title: '交易',
                content: `你要给对方什么物品`,
                titleBackgroundColor: new GameRGBAColor(1.00,1.00,1.00,1.00),
                contentBackgroundColor: new GameRGBAColor(0.00,0.00,0.00,1.00),
                options: show_list,
            });
            if (!bager){
                customer.player.directMessage('交易终止!');
                entity.player.directMessage('交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
            things2.id = customer.bagList[bager.index].id;
            const num = await customer.player.dialog<GameInputDialogParams>({
                type: GameDialogType.INPUT,
                title: '交易',
                content: `你要给对方多少个物品`,
                titleBackgroundColor: new GameRGBAColor(1.00,1.00,1.00,1.00),
                contentBackgroundColor: new GameRGBAColor(0.00,0.00,0.00,1.00),
            });
            if (!convertToNumber(num)){
                customer.player.directMessage('你输入错误，交易终止!');
                entity.player.directMessage('对方输入错误，交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
            if (num.includes('.')){
                customer.player.directMessage('你输入错误，交易终止!');
                entity.player.directMessage('对方输入错误，交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
            things2.number = convertToNumber(num);
            if (things2.number>customer.things_num(things2.id)){
                customer.player.directMessage('你没有这么多物品，交易终止!');
                entity.player.directMessage('对方交易物品数量不足，交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
            if (things2.number<0){
                customer.player.directMessage('你输入错误，交易终止!');
                entity.player.directMessage('对方输入错误，交易终止!');
                entity.canJy = true;customer.canJy = true;
                return;
            }
        }


        let show_give_things:string = '交易详情\n';
        if (type1.value === '金币'){
            show_give_things+=entity.player.name+' 给出的物品:\n金币*'+jb1+'\n';
        }else if (type1.value === '物品'){
            show_give_things+=`${entity.player.name} 给出的物品:\n${get_thing_name_by_id(things1.id)}*${things1.number}\n`;
        }else{
            show_give_things+=entity.player.name+' 给出的物品:\n无\n';
        }
        show_give_things+='--------------------\n';
        if (type2.value === '金币'){
            show_give_things+=customer.player.name+' 给出的物品:\n金币*'+jb2+'\n';
        }else if (type2.value === '物品'){
            show_give_things+=`${customer.player.name} 给出的物品:\n${get_thing_name_by_id(things2.id)}*${things2.number}\n`;
        }else{
            show_give_things+=customer.player.name+' 给出的物品:\n无\n';
        }

        const isAgree1 = await entity.player.dialog<GameSelectDialogParams>({
            type: GameDialogType.SELECT,
            title: '交易',
            content: show_give_things,
            titleBackgroundColor: new GameRGBAColor(1.00,1.00,1.00,1.00),
            contentBackgroundColor: new GameRGBAColor(0.00,0.00,0.00,1.00),
            options: ['接受交易','取消'],
        });
        if (!isAgree1){
            customer.player.directMessage('对方取消了交易，交易终止!');
            entity.player.directMessage('你取消了交易，交易终止!');
            entity.canJy = true;customer.canJy = true;
            return;
        }
        if (isAgree1.value === '取消'){
            customer.player.directMessage('对方取消了交易，交易终止!');
            entity.player.directMessage('你取消了交易，交易终止!');
            entity.canJy = true;customer.canJy = true;
            return;
        }
        const isAgree2 = await customer.player.dialog<GameSelectDialogParams>({
            type: GameDialogType.SELECT,
            title: '交易',
            content: show_give_things,
            titleBackgroundColor: new GameRGBAColor(1.00,1.00,1.00,1.00),
            contentBackgroundColor: new GameRGBAColor(0.00,0.00,0.00,1.00),
            options: ['接受交易','取消'],
        });
        if (!isAgree2){
            entity.player.directMessage('对方取消了交易，交易终止!');
            customer.player.directMessage('你取消了交易，交易终止!');
            entity.canJy = true;customer.canJy = true;
            return;
        }
        if (isAgree2.value === '取消'){
            entity.player.directMessage('对方取消了交易，交易终止!');
            customer.player.directMessage('你取消了交易，交易终止!');
            entity.canJy = true;customer.canJy = true;
            return;
        }

        if (type1.value === '金币'){
            entity.coin -= jb1;
            customer.coin +=jb1;
        }else if (type1.value === '物品'){
            entity.delete(things1);
            customer.add(things1,true);
        }
        if (type2.value === '金币'){
            customer.coin -= jb2;
            entity.coin +=jb2;
        }else if (type2.value === '物品'){
            customer.delete(things2);
            entity.add(things2,true);
        }
        entity.player.directMessage('交易成功!');
        customer.player.directMessage('交易成功!');
        entity.canJy = true;
        customer.canJy = true;
    }
})

const phb = world.querySelector('#排行榜');
phb.enableInteract = true;
phb.interactRadius = 6;
phb.interactHint = '点击这里查看排行榜';
phb.interactColor = new GameRGBColor(255,255,255);
phb.showEntityName = true;
phb.onInteract(async({entity})=>{
    const types = await entity.player.dialog<GameSelectDialogParams>({
        type: GameDialogType.SELECT,
        title: '排行榜',
        content: `你好！${entity.player.name}
你要查看什么排行榜？`,
        //titleBackgroundColor: new GameRGBAColor(1.00,1.00,1.00,1.00),
        //contentBackgroundColor: new GameRGBAColor(0.00,0.00,0.00,1.00),
        options: ['金币排行榜','等级排行榜','灵石排行榜'],
    });
    if (!types) return;
    if (types.value === '金币排行榜'){
        await entity.player.dialog<GameSelectDialogParams>({
            type: GameDialogType.SELECT,
            title: '排行榜',
            content: await leaderBoard('coin'),
            //titleBackgroundColor: new GameRGBAColor(1.00,1.00,1.00,1.00),
            //contentBackgroundColor: new GameRGBAColor(0.00,0.00,0.00,1.00),
            options: ['确定'],
        });
    }else if (types.value === '等级排行榜'){
        await entity.player.dialog<GameSelectDialogParams>({
            type: GameDialogType.SELECT,
            title: '排行榜',
            content: await leaderBoard('level'),
            //titleBackgroundColor: new GameRGBAColor(1.00,1.00,1.00,1.00),
            //contentBackgroundColor: new GameRGBAColor(0.00,0.00,0.00,1.00),
            options: ['确定'],
        });
    }else if (types.value === '灵石排行榜'){
        await entity.player.dialog<GameSelectDialogParams>({
            type: GameDialogType.SELECT,
            title: '排行榜',
            content: await leaderBoard('lingshi'),
            //titleBackgroundColor: new GameRGBAColor(1.00,1.00,1.00,1.00),
            //contentBackgroundColor: new GameRGBAColor(0.00,0.00,0.00,1.00),
            options: ['确定'],
        });
    }
})


const qiandao = world.querySelector('#签到');
qiandao.enableInteract = true;
qiandao.interactRadius = 6;
qiandao.interactHint = '';
qiandao.showEntityName = true;

qiandao.onInteract(async ({ entity }) => {
    const today = new Date();
    const todayDate = today.getFullYear() * 10000 + (today.getMonth() + 1) * 100 + today.getDate();

    if (entity.sign !== todayDate) {
        entity.sign = todayDate;
        entity.coin += 200;
        entity.exp += 50;

        entity.player.directMessage( "签到成功！获得了金币*200,经验*50,欢迎明天再来~");
    } else {
        entity.player.directMessage("你今天已经签过到了哦！请明天再来签到~");
    }
});